package mylist;

import java.util.Arrays;

public class MyArray implements IList{
    //定义一个顺序表，其实就是一个数组
    public int[] elem;
    //定义一个 usedSize，和数组的数据一起实时更新
    public int usedSize;
    public static final int DEFAULT_SIZE=10;
    public MyArray(){
        this.elem=new int[DEFAULT_SIZE];
    }
    private boolean isFull(){
        return usedSize==elem.length;
    }
    //扩容方法的实现
    private void checkExpansion(){
        if (isFull()){
            elem=Arrays.copyOf(elem,elem.length*2);
        }
    }
    @Override
    public void add(int data) {
        //如果数组满了怎么办？扩容
        checkExpansion();
        this.elem[usedSize]=data;
        usedSize++;
    }

    private void isLegal(int pos) throws PosLegitimate{
        if(pos<0||pos>usedSize){
            System.out.println("不合法");
            throw new PosLegitimate("pos下标异常"+pos);
        }
    }
    private void isLegalGetAndSet(int pos) throws MyArrayEmpty{
        if(pos<0||pos>=usedSize){
            System.out.println("不合法");
            throw new MyArrayEmpty("获取指定元素下标异常");
        }
    }
    @Override
    public void add(int pos, int data) {
        //1，先判断pos的合法性
        try{
            isLegal(pos);
        }catch (PosLegitimate e){
            e.printStackTrace();
        }
        checkExpansion();

        for (int i = usedSize-1; i < pos; i--) {
            elem[i+1]=elem[i];
        }
        elem[pos]=data;
        usedSize++;
    }

    @Override
    public boolean contains(int toFind) {
        if (isEmpty()){
            return false;
        }
        for (int i = 0; i < usedSize; i++) {
            if(elem[i]==toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        if (isEmpty()){
            return -1;
        }
        for (int i = 0; i < usedSize; i++) {
            if(elem[i]==toFind){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        isLegalGetAndSet(pos);
        return elem[pos];
    }

    @Override
    public void set(int pos, int value) {
        isLegalGetAndSet(pos);
        elem[pos]=value;
    }

    @Override
    public void remove(int toRemove) {
        int index=indexOf(toRemove);
        if(index==-1){
            System.out.println("找不到");
            return;
        }
        for (int i = index; i < usedSize-1; i++) {
            elem[i]=elem[i+1];
        }
        usedSize--;
    }

    @Override
    public int size() {
        return this.usedSize;
    }

    @Override
    public void clear() {
        this.usedSize=0;
    }

    @Override
    public void display() {
        for (int i = 0; i <usedSize; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }

    @Override
    public boolean isEmpty() {
        return usedSize==0;
    }
}
